package com.ruoyi.web.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.business.entity.YytCompany;
import com.ruoyi.common.business.entity.YytMember;
import com.ruoyi.common.business.service.YytCompanyService;
import com.ruoyi.common.business.service.YytMemberService;
import com.ruoyi.common.elasticsearch.domain.EsShopDoc;
import com.ruoyi.common.elasticsearch.service.EsShopDocService;
import com.ruoyi.common.pms.dao.YytShopMapper;
import com.ruoyi.common.pms.dao.YytShopMemberMapper;
import com.ruoyi.common.pms.entity.YytShop;
import com.ruoyi.common.pms.entity.YytShopMember;
import com.ruoyi.common.pms.service.*;
import com.ruoyi.common.ums.entity.YytUmsMemberCollectShop;
import com.ruoyi.common.ums.service.YytUmsMemberCollectShopService;
import com.ruoyi.utils.LoginUtils;
import com.ruoyi.utils.RedisService;
import com.ruoyi.utils.ResponseResult;
import com.ruoyi.vo.SpuInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 店铺相关接口
 *
 * @author tanxingxian
 * @date 2021-12-23 09:05
 */
@RestController
@RequestMapping("/shop")
public class ShopController {

    @Autowired
    private RedisService redisService;
    @Autowired
    private YytShopService yytShopService;
    @Autowired
    private YytShopMapper yytShopMapper;
    @Autowired
    private YytMemberService yytMemberService;
    @Autowired
    private YytCompanyService yytCompanyService;
    @Autowired
    private YytShopNoticeService yytShopNoticeService;
    @Autowired
    private YytPmsSkuInfoService yytPmsSkuInfoService;
    @Autowired
    private YytUmsMemberCollectShopService yytUmsMemberCollectShopService;
    @Autowired
    private EsShopDocService esShopDocService;
    @Autowired
    private YytPmsSpuInfoService yytPmsSpuInfoService;
    @Autowired
    private YytShopMemberService yytShopMemberService;


    /**
     * 根据店铺id获取店铺信息
     */
    @GetMapping("/getInfo")
    public ResponseResult getInfo(@RequestParam("id") String shopId) {
        return ResponseResult.success(yytShopService.getById(shopId));
    }

    /**
     * 获取店铺商品列表
     */
    @GetMapping("/getSkuList")
    public ResponseResult getSkuList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                     @RequestParam("shopId") String shopId,
                                     @RequestParam("searchVal") String searchVal) {
        return ResponseResult.success(yytPmsSkuInfoService.getPage(new Page<>(pageNum, 10), shopId, searchVal));
    }

    /**
     * 店铺关注（取消关注）
     */
    @PostMapping("/follow")
    public ResponseResult follow(@RequestBody YytUmsMemberCollectShop collectShop) {
        collectShop.setMemberId(LoginUtils.getLoginUser(redisService).getId());
        return ResponseResult.success(yytUmsMemberCollectShopService.follow(collectShop));
    }

    /**
     * 店铺是否已关注
     */
    @GetMapping("/isFollowed")
    public ResponseResult isFollowed(@RequestParam("shopId") String shopId) {
        if (!StpUtil.isLogin()) {
            return ResponseResult.success(false);
        }
        String memberId = LoginUtils.getLoginUser(redisService).getId();
        synchronized (memberId.intern()) {
            LambdaQueryWrapper<YytUmsMemberCollectShop> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YytUmsMemberCollectShop::getShopId, shopId);
            wrapper.eq(YytUmsMemberCollectShop::getMemberId, memberId);
            YytUmsMemberCollectShop collectShop = yytUmsMemberCollectShopService.getOne(wrapper);
            return ResponseResult.success(null != collectShop);
        }
    }

    /**
     * 获取店铺公告列表
     */
    @GetMapping("/getNoticeList")
    public ResponseResult getNoticeList(@RequestParam("shopId") String shopId) {
        return ResponseResult.success(yytShopNoticeService.getNotices(shopId));
    }

    /**
     * 申请入驻
     */
    @PostMapping("/applyJoin")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult applyJoin(@RequestBody YytShop yytShop) throws IOException {
        if (StringUtils.isNotBlank(yytShop.getId())) {
            return ResponseResult.failure("数据异常, 已拒绝处理");
        }
        YytMember loginUser = LoginUtils.getLoginUser(redisService);

        yytShop.setState("0");
        yytShop.setOwnerId(loginUser.getId());
        yytShop.setOwnerName(loginUser.getNickname());
        yytShop.setCreateBy(loginUser.getUsername());
        yytShopMapper.insert(yytShop);

        // 插入用户和店铺绑定关系
        YytShopMember yytShopMember = new YytShopMember();
        yytShopMember.setMemberId(loginUser.getId());
        yytShopMember.setShopId(yytShop.getId());
        yytShopMember.setShopName(yytShop.getShopName());
        yytShopMember.setWechatId(loginUser.getWechatId());
        yytShopMember.setAuthStatus("1");
        yytShopMemberService.save(yytShopMember);


        YytCompany company = yytShop.getCompany();
        company.setShopId(yytShop.getId());
        company.setCreateBy(yytShop.getCreateBy());
        yytCompanyService.save(company);
        EsShopDoc esShopDoc = new EsShopDoc();
        BeanUtils.copyProperties(yytShop, esShopDoc);
        // 添加时暂时不插入es, 审核通过再添加到es
//        Boolean aBoolean = esShopDocService.saveShopDoc(esShopDoc);
        return ResponseResult.success();
    }

    /**
     * 获取我的店铺列表
     * @return
     */
    @GetMapping("/myShopList")
    public ResponseResult getMyShopList(String wechatId){
        return ResponseResult.success(yytShopService.getMyShopAll(wechatId));
    }

    /**
     * 添加商品
     * @param spuInfoVo
     * @return
     */
    @PostMapping("/addSpuInfoData")
    public ResponseResult addSpuInfoData(@RequestBody SpuInfoVo spuInfoVo){
        return ResponseResult.success(yytPmsSpuInfoService.insertYytPmsSpuInfo(spuInfoVo));
    }

    /**
     * 获取店铺营业状态
     * @param shopId
     * @return
     */
    @GetMapping("/getShopOnlineStatus")
    public ResponseResult getShopOnlineStatus(@RequestParam("shopId") String shopId){
        return ResponseResult.success(yytShopService.getById(shopId));
    }

    /**
     * 修改店铺营业状态
     * @param id
     * @return
     */
    @GetMapping("/updateOnlineStatus")
    public ResponseResult updateOnlineStatus(@RequestParam("id") String id, @RequestParam("onlineStatus") String status){
        UpdateWrapper<YytShop> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id).set("online_status", status);
        return ResponseResult.success(yytShopService.update(wrapper));
    }

    /**
     * 获取店铺及配送员联系电话
     * @param shopId
     * @return
     */
    @GetMapping("/getShopPhone")
    public ResponseResult getShopPhone(@RequestParam("shopId") String shopId){
        QueryWrapper<YytCompany> wrapper = new QueryWrapper<>();
        wrapper.eq("shop_id", shopId);
        YytCompany company = yytCompanyService.getOne(wrapper, false);
        QueryWrapper<YytShopMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", shopId).eq("pass_status", 1).eq("auth_status", 2);
        List<YytShopMember> shopMembers = yytShopMemberService.list(queryWrapper);
        List<String> pList = new ArrayList<>();
        for (YytShopMember yytShopMember : shopMembers){
            QueryWrapper<YytMember> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("id", yytShopMember.getMemberId());
            YytMember member = yytMemberService.getOne(wrapper1, false);
            if(member != null){
                pList.add(member.getPhone());
            }
        }

        Map result = new HashMap<>();
        if(company != null){
            result.put("answer", company.getPhone());
        }
        result.put("inform", pList);

        return ResponseResult.success(result);
    }

}
